package com.uaf.vxalipaybill.provider.shardingjdbc;

import java.util.Collection;
import java.util.HashMap;
import java.util.SortedMap;
import java.util.stream.Collectors;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.shardingsphere.core.rule.DataNode;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.springframework.stereotype.Component;

import com.uaf.log.MySlf4j;

/**
 * @filename InitTableNodesToHashLoop.java
 * @description
 * @author 马庆智
 * @date 2022/3/31 16:34
 */
@Component
public class InitTableNodesToHashLoop {

	@Resource
	private ShardingDataSource shardingDataSource;

	private HashMap<String, SortedMap<Long, String>> tableVirtualNodes = new HashMap<String,
			SortedMap<Long, String>>();

	@PostConstruct
	public void init() {
		try {
			ShardingRule rule = shardingDataSource.getShardingContext().getShardingRule();

			Collection<TableRule> tableRules = rule.getTableRules();
			ConsistentHashAlgorithm consistentHashAlgorithm = new ConsistentHashAlgorithm();
			for (TableRule tableRule : tableRules) {
				String logicTable = tableRule.getLogicTable();

				tableVirtualNodes.put(logicTable, consistentHashAlgorithm.initNodesToHashLoop(
						tableRule.getActualDataNodes().stream().map(DataNode::getTableName)
								.collect(Collectors.toList())));
			}
			MySlf4j.textInfo("tableVirtualNodes:{0}", tableVirtualNodes);
		} catch (Exception e) {

		}
	}

	public HashMap<String, SortedMap<Long, String>> getTableVirtualNodes() {
		return tableVirtualNodes;
	}

	public void setTableVirtualNodes(HashMap<String, SortedMap<Long, String>> tableVirtualNodes) {
		this.tableVirtualNodes = tableVirtualNodes;
	}
}
